from moxi_server.src.Gemini.Function import __start_web__, __kill_browser__
from moxi_server.src.Web import *


class Web:
    def __init__(self, host: str = '0.0.0.0', port: int = 5000, debug: bool = False):
        self.gemini = None
        self.app = Flask(__name__, template_folder="templates", static_folder="static")
        self.host = host
        self.port = port
        self.debug = debug

        self.api_key = getUserConfig()["google_api_key"]
        self.gemini = OriginGemini(apiKey=self.api_key)

        self.geminiByUsername: dict[str, OriginGemini] = {}

    def appRun(self):
        self.app.route("/", methods=["GET", "POST"])(self.index)
        self.app.route("/chat/<string:username>", methods=["GET"])(self.chat)
        self.app.route("/chatTo", methods=["POST"])(self.chatWithBy)
        self.app.route("/options", methods=["GET"])(self.options)
        self.app.route("/loadConfig", methods=["POST"])(self.loadConfig)

    @staticmethod
    def index():
        return redirect("/options")

    def options(self):
        return render_template("options.html", models=self.gemini.getShowModelNames()[4:])

    def loadConfig(self):
        data = request.get_json()
        if not data:
            return redirect("/options")
        else:
            username = data["username"]
            nickname = data["nickname"]
            model = data["model"]
            personality = modelType = data["personality"]
            customDescription = data["customDescription"]
            match personality:
                case "聊天型：萝莉":
                    personality = Personality(callName=nickname).loli()
                case "聊天型：妹妹":
                    personality = Personality(callName=nickname).sister()
                case "专业型：程序员":
                    personality = Personality(callName=nickname).programmer()
                case "专业型：翻译官":
                    personality = Personality(callName=nickname).translator()
                case "自定义":
                    personality = customDescription
                    pass
            self.geminiByUsername[username] = OriginGemini(apiKey=self.api_key, userName=username, callName=nickname,
                                                           modelType=modelType,
                                                           system_instruction=personality)
            self.geminiByUsername[username].choiceModel(model)
        return jsonify({"status": "ok"})

    def chat(self, username: str = "用户"):
        """
        需要传入设定参数，参数可变，没有就重定向
        callName, username, modelName, system_instruction
        这些参数直接封装在函数中，一次调用
        """
        if username not in self.geminiByUsername:
            return redirect("/options")
        self.geminiByUsername[username].establishChat(enable_automatic_function_calling=True)
        return render_template("chat.html", gemini=self.geminiByUsername[username])

    def chatWithBy(self):
        data = request.get_json()
        return Response(self.geminiByUsername[data["username"]].chatWith(data["msg"]), mimetype="text/html")

    def run(self) -> None:
        __start_web__()
        self.appRun()
        self.app.run(host=self.host, port=self.port, debug=self.debug)
        __kill_browser__()


def runner():
    Web(port=800).run()


if __name__ == "__main__":
    # import os
    # print(os.environ)
    runner()
